package com.example.zuoye.controller;

import com.example.zuoye.entity.User;
import com.example.zuoye.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/shop")
public class ShopController {
    @Autowired
    private UserService userService;

    User user = new User();

    /**
     * 访问shop/shoplogin路径
     * @return shoplogin,返回shoplogin前端页面
     */
    @RequestMapping("/shoplogin")
    public String shoplogin(){
        return "shoplogin";
    }

    /**
     * 登录功能,前端点击登录按钮,根据前端的username,password,查看数据库中是否存在
     * @param request
     * @param session
     * @param model
     * @return  成功:跳转到/shopManage 前端页面
     *          失败:shoplogin,返回前端shoplogin页面
     * @throws Exception
     */
    @RequestMapping("/ushoplogin")
    public String login(HttpServletRequest request,
                        HttpSession session,
                        Model model) throws Exception{

        System.out.println("执行了ushoplogin方法");

        // 获取前端的username,password
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 通过用户名查询数据库，判断用户是否存在
        // 不存在跳转至注册页面
        String usernameDB = userService.findUserNameByUserName(username);
        if (usernameDB == null){
            System.out.println("该用户名不存在");
            // 返回 该用户名不存在 信息给前端
            model.addAttribute("tip_registered","该用户名不存在");
            return "shoplogin";
        }

        // 数据库中,根据username,password查询用户信息
        user = userService.checkByUP(username, password);
        // 用户user存在于数据库中
        if (user != null){
            // 若user存在写入session
            session.setAttribute("user_login",user);
            // 跳转到/good/goodManage前端页面
            return "redirect:/good/goodManage";
        }else{
            // 返回 密码不正确 信息给前端
            model.addAttribute("tip_registered","密码不正确");
            return "shoplogin";
        }
    }
}
